package com.ddtech.business.web.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ddtech.business.common.BaseEntity;
import com.ddtech.business.common.BaseService;
import com.ddtech.business.constant.BusinessEnum;
import com.ddtech.business.course.entity.CourseResource;
import com.ddtech.business.course.service.CourseResourceService;
import com.ddtech.business.train.entity.TrainPlanResource;
import com.ddtech.business.train.service.TrainPlanResourceService;
import com.ddtech.business.web.entity.Answer;
import com.ddtech.business.web.mapper.AnswerMapper;
import com.ddtech.business.web.query.AnswerQuery;
import com.ddtech.business.web.res.AnswerCheckVo;
import com.ddtech.business.web.res.AnswerPcVo;
import com.ddtech.business.web.res.AnswerTreeVo;
import com.ddtech.business.web.service.AnswerService;
import com.ddtech.exception.BizPreconditions;
import com.ddtech.utils.PageUtil;
import com.ddtech.utils.SecurityUtils;
import com.ddtech.utils.StringUtils;
import com.ddtech.utils.TreeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 问答表 服务实现类
 * </p>
 *
 * @author bin_pu
 * @since 2023-02-06
 */
@Service
public class AnswerServiceImpl extends BaseService<AnswerMapper, Answer> implements AnswerService {

    @Resource
    private  AnswerMapper answerMapper;

    @Autowired
    private CourseResourceService courseResourceService;

    @Autowired
    private TrainPlanResourceService trainPlanResourceService;

    @Override
    public Object pageList(AnswerQuery answerQuery) {
        IPage<Answer> page = this.page(answerQuery.populatePage(), answerQuery.autoWrapper());
        return PageUtil.toPage(page.getRecords(), page.getTotal());
    }

    /***
     * description:查询待回复的问答
     * @param:  * @param answerQuery
     * @date: 2023-06-07
     * @return: java.lang.Object
     * @version v1.0
     * @author:wei_zhang(xiao)
     */
    @Override
    public Object getPageNoAnswerListPc(AnswerQuery answerQuery) {
        if(answerQuery.isSelf()){
            answerQuery.setUserId(SecurityUtils.getUserId());
        }
        List<AnswerPcVo> answerList = answerMapper.getPageNoAnswerListPc(answerQuery);
        List<AnswerTreeVo> data = answerList.stream().map(map -> JSON.parseObject(JSON.toJSONString(map), AnswerTreeVo.class))
                .sorted(Comparator.comparing(AnswerTreeVo::getUpdateTime, Comparator.reverseOrder()))
                .collect(Collectors.toList());
        List<AnswerTreeVo> treeData= TreeUtils.buildListToTree(data);
        List list = PageUtil.toPage(answerQuery.getPage() - 1, answerQuery.getSize(), treeData);
        return PageUtil.toPage(list, treeData.size());
    }


    @Override
    public Object getPageListPc(AnswerQuery answerQuery) {
        if(answerQuery.isSelf()){
            answerQuery.setUserId(SecurityUtils.getUserId());
        }
        List<AnswerPcVo> answerList = answerMapper.getPageListPc(answerQuery);
        //List<Answer> answerList =this.list(answerQuery.autoWrapper());
        List<AnswerTreeVo> data = answerList.stream().map(map -> JSON.parseObject(JSON.toJSONString(map), AnswerTreeVo.class))
                .sorted(Comparator.comparing(AnswerTreeVo::getUpdateTime, Comparator.reverseOrder()))
                .collect(Collectors.toList());
        List<AnswerTreeVo> treeData= TreeUtils.buildListToTree(data);
        List list = PageUtil.toPage(answerQuery.getPage() - 1, answerQuery.getSize(), treeData);
        return PageUtil.toPage(list, treeData.size());
    }

    /**
     * description: 普通课程提问
     * @param:  * @param answer
     * @date: 2023-06-27
     * @return: void
     * @version v1.0
     * @author:wei_zhang(xiao)
     */
    @Override
    public void create(Answer answer) {
        answer.init();
        if (StringUtils.isBlank(answer.getId())) {
            answer.setStatus(0);
        }
        //提问
        if(answer.getType()==1){
            CourseResource courseResource= courseResourceService.getById(answer.getChapterId());
            if (courseResource!=null) {
                answer.setChapterName(courseResource.getResourceName());
            }
        }
        answer.setUserId(SecurityUtils.getUserId());
        answer.setUserName(SecurityUtils.getName());
        this.saveOrUpdate(answer);
    }

    /**
     * description: 培训课程提问
     * @param:  * @param answer
     * @date: 2023-06-27
     * @return: void
     * @version v1.0
     * @author:wei_zhang(xiao)
     */
    @Override
    public void trainCreate(Answer answer) {
        answer.init();
        if (StringUtils.isBlank(answer.getId())) {
            answer.setStatus(0);
        }
        //提问
        if(answer.getType()==1){
            TrainPlanResource trainPlanResource= trainPlanResourceService.getById(answer.getChapterId());
            if (trainPlanResource!=null) {
                answer.setChapterName(trainPlanResource.getResourceName());
            }
        }
        answer.setUserId(SecurityUtils.getUserId());
        answer.setUserName(SecurityUtils.getName());
        this.saveOrUpdate(answer);
    }

    @Override
    public void del(String id) {
        QueryWrapper<Answer> noteQueryWrapper = this.newValidQueryWrapper();
        noteQueryWrapper.eq(BaseEntity.ID, id);
        List<String> roleCode = SecurityUtils.getRoleCode();
        if (!roleCode.contains("ADMIN")) {
            noteQueryWrapper.eq(Answer.USER_ID, SecurityUtils.getUserId());
        }
        Answer answer = this.getOne(noteQueryWrapper);
        BizPreconditions.check(answer == null, BusinessEnum.QUERY_ERROR.getMsg());
        answer.baseDelete();
        this.saveOrUpdate(answer);
    }

    @Override
    public void checkAll(AnswerCheckVo checkVo) {
        for (String id : checkVo.getIds()) {
            Answer answer = this.getById(id);
            BizPreconditions.check(answer == null, BusinessEnum.QUERY_ERROR.getMsg());
            answer.setStatus(checkVo.getStatus());
            answer.setRemark(checkVo.getRemark());
            this.saveOrUpdate(answer);
        }
    }
}
